<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:50px">
      <el-input v-model="listQuery.companyCode" placeholder="公司编号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.companyName" placeholder="公司名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      

      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left:200px" @click="handleFilter()">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData()">
        重置
      </el-button>
    </div>


    <el-row :gutter="10" class="mb8" style="margin-bottom:20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          disabled
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          disabled
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          disabled
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table 
        v-loading="listloading" 
        :data="list" 
        element-loading-text="Loading"
        border
        highlight-current-row>

        <el-table-column align="center" label="序号">
          <template slot-scope="scope">
              {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="公司编号">
          <template slot-scope="scope">
              {{ scope.row.companyCode }}
          </template>
        </el-table-column>
 
        <el-table-column align="center" label="公司名称">
          <template slot-scope="scope">
              {{ scope.row.companyName }}
            </template>
        </el-table-column>
 
        <el-table-column align="center" label="法人">
          <template slot-scope="scope">
              {{ scope.row.companyMan }}
          </template>
        </el-table-column>
 
        <el-table-column align="center" label="电话">
          <template slot-scope="scope">
              {{ scope.row.companyteleNumber }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="传真" width="200">
          <template slot-scope="scope">
              {{ scope.row.companyCh }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="地址" width="150">
          <template slot-scope="scope">
              {{ scope.row.companyAdress }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="邮箱" width="150">
          <template slot-scope="scope">
              {{ scope.row.companyEmail }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="网址">
          <template slot-scope="scope">
              {{ scope.row.companyWebAdress }}
          </template>
        </el-table-column>

        <el-table-column label="Actions" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleEdit(row)" plain>
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)" plain>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pagesize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total">
    </pagination>

    <!-- //对话框   -->
    <el-dialog :title="formTitle[dialogState]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="公司编号" prop="companyCode" label-width="80px">
          <el-input v-model="temp.companyCode" placeholder="请填写公司编号" />
        </el-form-item>
        <el-form-item label="用户名称" prop="companyName" label-width="80px">
          <el-input v-model="temp.companyName" placeholder="请填写用户名称" />
        </el-form-item>

        <el-form-item label="法人" prop="companyMan" label-width="80px">
          <el-input v-model="temp.companyMan" placeholder="请填写法人" />
        </el-form-item>
        <el-form-item label="电话" prop="companyteleNumber" label-width="80px">
          <el-input v-model="temp.companyteleNumber" placeholder="请填写电话" />
        </el-form-item>

        <el-form-item label="传真" prop="companyCh" label-width="80px">
          <el-input v-model="temp.companyCh" placeholder="请填写用户密码" />
        </el-form-item>

        <el-form-item label="地址" prop="companyAdress" label-width="80px">
          <el-input v-model="temp.companyAdress" placeholder="请填写地址" />
        </el-form-item>

        <el-form-item label="邮箱" prop="companyEmail" label-width="80px">
          <el-input v-model="temp.companyEmail" placeholder="请填写用户密码" />
        </el-form-item>

        <el-form-item label="网址" prop="companyWebAdress" label-width="80px">
          <el-input v-model="temp.companyWebAdress" placeholder="请填写用户密码" />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogState==='add'?AddData():editData()">
          确定
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { editCompanyInfo ,addCompanyInfo,findCompanyInfo,getList}from '@/api/company'
// import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  components: { Pagination },
  //过滤器
  filters:{
    stateFilter(state){
      const stateMap = {
        启用:'success',
        禁用:'danger'
      }
      return stateMap[state]
    }
  },
  data() {
    return {
      list: null,
      total:0,
      listloading: true,
      dialogFormVisible: false,
      //查找
      listQuery:{
        userCode:undefined,
        userName:undefined,
        userGender:undefined,
        userRole:undefined,
        userState:undefined
      },
      //表格
      temp:{
        id:undefined,
        companyCode:'',
        companyName:'',
        companyMan:'',
        companyteleNumber:'',
        companyCh:'',
        companyAdress:'',
        companyEmail:'',
        companyWebAdress:''
      },
      // 校验规则
      rules:{
        //验证用户编号——只能数字+英文,不能包含特殊字符
        companyCode: [{ required: true, message: '公司编号不能为空', trigger: 'blur' },
          {pattern:/^[a-zA-Z0-9]+$/, message: '不能包含特殊字符', trigger: ['blur','change'] },
          {min:2, max:6 ,message:'公司用户编号不少于2位不长于6位',trigger:['blur','change']}],
        companyName: [{ required: true, message: '用户名称不能为空', trigger:  'blur' },
          {min:2, max:10 ,message:'用户名称不少于2位不长于10位',trigger:['blur','change']}],
        companyMan:[{ required: true, message: '用户名称不能为空', trigger:  'blur' },
          {min:2, max:10 ,message:'用户名称不少于2位不长于10位',trigger:['blur','change']}],
        //验证号码
        companyteleNumber: [{ required: true, message: '号码不能为空', trigger: 'blur' },
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,message: '请填写正确的手机号码', trigger: ['blur','change'] }],
        //验证邮箱
        companyEmail: [{ required: true, message: '邮箱不能为空', trigger: ['blur','change'] },
          {type:'email', message: '请填写正确的邮箱', trigger: ['blur','change'] }],
          //传真
        companyCh: [{ required: true, message: '传真不能为空', trigger: 'blur' },
          { pattern:/^[a-zA-Z0-9]+$/, message: '不能包含特殊字符', trigger: ['blur','change'] }],
        companyAdress:[{ required: true, message:'地址不能为空',trigger:'blur'}],
        companyWebAdress:[{ required: true, message:'网址不能为空',trigger:'blur'}]
      },
      //数据分页
      currentPage:  1,    //初始页
      pagesize: 5,      //每页的数据
      arr:[],    //你的数据
      roles:['管理员','普通用户'],       //角色
      formTitle:{       //弹窗标题
        add:'新增公司信息',
        edit:'修改公司信息'
      },
      dialogState:''    //弹窗标题 
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    //查找函数
    handleFilter() {
      console.log('我被点击了!')
      this.listloading = true
      findCompanyInfo(this.listQuery).then(response =>{
        this.list = response.data.items
        this.total = response.data.total
        console.log(this.list)
        this.listloading = false
      })
    },
    //分页函数
    handleCurrentChange(val){
      this.currentPage = val;  
      console.log("当前页面显示xxx页",val)
      // this.getList(); //确定当前页面后刷新页面
    },  
    //每页显示几条
    handleSizeChange(val){
      this.pagesize = val;  //获取pagesize里的每页显示几条数据，赋给自定义的PageNUm
      console.log("当前页面显示xxx条",val)
      // this.getList(); //展示页面信息
    },
    fetchData(){
        this.listloading = true
        getList().then(response =>{
            this.list = response.data.items
            this.total = response.data.total
            // console.log(this.total)
            this.listloading = false
        })
    },
    //每次点击添加按钮重置表单
    resetTemp(){
      this.temp = {
        id:undefined,
        companyCode:'',
        companyName:'',
        companyMan:'',
        companyteleNumber:'',
        companyCh:'',
        companyAdress:'',
        companyEmail:'',
        companyWebAdress:''
      }
    },
    //添加按钮触发事件 Add按钮绑定函数
    handleAdd(){
      this.resetTemp()
      this.dialogState = 'add'
      this.dialogFormVisible = true
      this.$nextTick(()=>{
        //重置表单校验
        this.$refs['dataForm'].clearValidate()
      })
      console.log("新增按钮被点击了！")
    },
    //新增用户信息表单确定按钮
    AddData(){
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          //id如何实现自增，待解决!!!
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          addCompanyInfo(this.temp).then(()=>{
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            //消息提示
            this.$notify({
              title: 'Success',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //编辑操作
    handleEdit(row){
      this.temp = Object.assign({}, row) // copy obj
      this.dialogState = 'edit'
      this.dialogFormVisible = true
      console.log("编辑按钮被点击了")
      this.$nextTick(() => {
        //重置表单校验
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑信息
    editData(){
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          const tempData = Object.assign({}, this.temp)
          editCompanyInfo(tempData).then(()=>{
            //findIndex()寻找下标，满足返回位置，反之-1
            const index = this.list.findIndex(v => v.id === this.temp.id)
            //splice从index位置，替换1个，用this.temp的内容
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //删除操作
    handleDelete(row,index){
      // this.dialogFormVisible = true
      //vue2直接用$confirm
      this.$confirm('是否删除该条信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.list.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      console.log("删除按钮被点击了")
    }
  }
}
</script>
